#coding=utf-8
import logging, time
from google.appengine.ext import webapp
from google.appengine.api.labs import taskqueue
from google.appengine.ext import db

from models import Stock, TradableShare,create_stock
from stockcrawler import get_stock, get_ts, get_codes

def now():
    import time
    time_format = "%Y-%m-%d %H:%M:%S"
    return time.strftime(time_format)
    
class Updater(webapp.RequestHandler):
    def get(self):
        codes = get_codes('sz') + get_codes('sh')
        codes_in_db = [s.code for s in Stock.all()]
        
        logging.info( "Num of stock in db:%i"%len(codes_in_db) )
        logging.info( "Num of stock in sina:%i"%len(codes) )
        
        new_codes = list(set(codes) - set(codes_in_db))   
        logging.info( "Num of new stock:%i"%len(new_codes) )
        
        for code in new_codes:           
            taskqueue.add(url='/new_stock', method='GET', params={'code': code})
        for code in codes_in_db:
            taskqueue.add(url='/update_ts', method='GET', params={'code': code})
                   
class TsUpdater(webapp.RequestHandler):
    def get(self):
        #logging.info('update_ts GET called on%s'%now())
        
        code = self.request.get('code')
        s = Stock.gql("WHERE code = :1", code).fetch(1)[0]
        if s:
            data = get_ts(code)[code]
            s.update_tss(data)
          
class NewStock(webapp.RequestHandler):
    def get(self):
        #logging.info('new_stock GET called on%s'%now())
        
        code = self.request.get('code')
        data = get_stock(code)
        s = create_stock(data)
        
        data = get_ts(code)[code]
        s.update_tss(data)

class Deleter(webapp.RequestHandler):
    def get(self):
        num = self.request.get('num')
        if not num:num=100
        else:
            num = int(num)
        m = self.request.get('model')
        
        q = db.GqlQuery('select * from %s'%m)
        results = q.fetch(num)
        db.delete(results)
        
class DeleteTaskUpdater(webapp.RequestHandler):
    def get(self):
        num = int(self.request.get('num'))
        m = self.request.get('model')
        for i in range(num):
            taskqueue.add(url='/delete', method='GET', params={'model':m})
            time.sleep(0.1)

class Test(webapp.RequestHandler):
    def get(self):
        p0 = time.time()
        codes = get_codes('sz') + get_codes('sh')
        p1 = time.time()
        logging.info('Time for Getting codes from sina: %i'%(p1 - p0))
        
        for i in range(len(codes)):
            c = codes[i]
            
            key_name = "stock_%s"%c
            s = Stock.get_by_key_name(key_name)
            '''
            if i%100 == 0:
                logging.info("%i"%i)
            '''
        p2 = time.time()
        logging.info('Time for searching in db: %i'%(p2 - p1))
        
        logging.info("%i"%len(codes))

class AddJob(webapp.RequestHandler):
    def get(self):
        url = '/test'
        params={}
        method='GET'
        
        taskqueue.add(url=url, method=method, params=params)
